package com.shuqi.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.widget.TextView;

import com.shuqi.activity.viewport.CommonTitle;
import com.shuqi.activity.viewport.CountDownTimmerView;
import com.shuqi.activity.viewport.PhoneEditTextView;
import com.shuqi.activity.viewport.ToastDialog;
import com.shuqi.application.ShuqiApplication;
import com.shuqi.common.utils.CheckInputUtils;
import com.shuqi.common.utils.RegexUtil;
import com.shuqi.controller.AccountBindController;
import com.shuqi.controller.AcountBindVerifyCodeController;
import com.shuqi.controller.MainController;
import com.shuqi.controller.R;
import com.shuqi.database.dao.impl.AccountDao;
import com.shuqi.database.model.UserInfo;
import com.shuqi.interfaces.EventTypeConstants;
import com.shuqi.interfaces.IEventListener;
import com.shuqi.model.AccountBindModel;
import com.shuqi.model.manager.MyAccountManager;
import com.shuqi.model.parse.parser.AccountBindGetValidationParser;
import com.shuqi.model.parse.parser.AccountBindGetValidationParser.AccountBindValidationInfo;
import com.shuqi.model.parse.parser.AccountBindParser;
import com.shuqi.model.parse.parser.AccountBindParser.AccountBindParserInfo;
import com.shuqi.model.parse.parser.AccountBindVerifyParser;
import com.shuqi.model.parse.parser.AccountBindVerifyParser.AccountBindByPhoneInfo;

public class AccountMobileBindActivity extends ActivityBase implements IEventListener,
        OnClickListener, OnFocusChangeListener {

    public static final int TYPE_REGISTER = 1001; // 注册传入的参数

    public static final int TYPE_BIND = 1002; // 绑定传入的参数

    public static final int TYPE_FINDPASSWORD = 1003;// 找回密码传入的参数

    private boolean isSeparatedText = true;

    public final static String INTENT_TYPE = "intent_type";

    private PhoneEditTextView mMobileText;

    private EditText mValidationText;

    private CountDownTimmerView mCountDownTimmerView;

    private TextView mNextView;

    private View mMobileView;

    private TextView mMobilePointTextView; // 提示语

    private TextView mVerifyCodePointTextView;// 提示语

    private AcountBindVerifyCodeController mAccountBindVerifyController;

    private AccountBindController mAccountBindController;

    private ToastDialog mLoadingDialog;

    private int mType;// 根据type区分是找回密码还是绑定手机 (1001注册,1002绑定,1003找回密码)


    private String mCurrentPhoneNumber;

    private CommonTitle mTitle;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_account_mobilebind);
        handlerIntent();
        isEmailOrMobileVipUser();
        mAccountBindVerifyController =
                (AcountBindVerifyCodeController) MainController.getMainManagerInstance()
                        .createController(MainController.ACCOUNT_ID_BIND, this);
        mAccountBindVerifyController.addEventListener(this);
        if (mType == TYPE_BIND) {
            mAccountBindController =
                    (AccountBindController) MainController.getMainManagerInstance()
                            .createController(MainController.CONTROLLER_ID_ACCOUNT_BINDPHONE, this);
            mAccountBindController.addEventListener(this);
        }
        initView();
        initTitle();
    }

    private void initView() {
        mTitle = (CommonTitle) findViewById(R.id.title);
        mTitle.setLeftClickListener(this);
        mMobileText = (PhoneEditTextView) findViewById(R.id.edit_mobile);
        mValidationText = (EditText) findViewById(R.id.edit_validation);
        mCountDownTimmerView = (CountDownTimmerView) findViewById(R.id.text_validation);
        mNextView = (TextView) findViewById(R.id.bind_next);
        mMobilePointTextView = (TextView) findViewById(R.id.mobile_point);
        mVerifyCodePointTextView = (TextView) findViewById(R.id.verify_code_point);
        mMobileView = findViewById(R.id.layout_mobile);

        mCountDownTimmerView.setOnClickListener(this);
        mNextView.setOnClickListener(this);
        mMobileText.addTextChangedListener(textWatcher);

        mMobileView.setSelected(true);
        mValidationText.setSelected(false);

        mMobileText.setOnFocusChangeListener(this);
        mValidationText.setOnFocusChangeListener(this);

    }

    private void initTitle() {
        if (mType == AcountBindVerifyCodeController.FINDPASSWORD_TYPE) {
            mTitle.setTitle(getString(R.string.findpassword_phone_find));
        }
    }

    private TextWatcher textWatcher = new TextWatcher() {

        @Override
        public void afterTextChanged(Editable editable) {
            if (isSeparatedText) {
                String mobileStr = mMobileText.getString();
                if (!TextUtils.isEmpty(mobileStr) && RegexUtil.isMobileNO(mobileStr)) {
                    separatedText(mobileStr, true);
                } else {
                    separatedText(mobileStr, false);
                }
            }
        }

        @Override
        public void beforeTextChanged(CharSequence charsequence, int i, int j, int k) {}

        @Override
        public void onTextChanged(CharSequence charsequence, int i, int j, int k) {}
    };

    private void separatedText(String inputText, boolean isRight) {
        isSeparatedText = false;
        if (isRight) {
            StringBuilder resultStr = new StringBuilder();
            resultStr.append(inputText.substring(0, 3)).append("-")
                    .append(inputText.substring(3, 7)).append("-").append(inputText.substring(7));
            mMobileText.setText(resultStr.toString());
            mMobileText.setSelection(resultStr.length());
            mMobilePointTextView.setVisibility(View.INVISIBLE);
        } else {
            mMobileText.setText(inputText);
            mMobileText.setSelection(inputText.length());
        }
        isSeparatedText = true;
    }

    @Override
    public void onClick(View view) {
        if(view.getId() == R.id.title_left){
            ActivityManager.getInstance().finishActivity(this);
        }
        if (view == mCountDownTimmerView) {
            getValidationCode();
        } else if (view == mNextView) {
            nextStepBind();
        }
    }

    private static final int COUNT_DOWN_MODE_LADING = 1;

    private static final int COUNT_DOWN_MODE_START = 2;

    private static final int COUNT_DOWN_MODE_RESET = 3;

    // 设置验证码textview的状态
    private void setCountDownTimmerView(int mode) {
        switch (mode) {
            case COUNT_DOWN_MODE_LADING:
                mCountDownTimmerView.setText("获取中");
                mCountDownTimmerView.setClickable(false);
                break;

            case COUNT_DOWN_MODE_START:
                mCountDownTimmerView.start();
                mCountDownTimmerView.setBackgroundResource(R.drawable.identify_code_n);
                mCountDownTimmerView.setTextColor(android.graphics.Color.parseColor("#b9b9b9"));
                break;

            case COUNT_DOWN_MODE_RESET:
                mCountDownTimmerView.setText("获取验证码");
                mCountDownTimmerView.setClickable(true);
                break;

            default:
                break;
        }
    }

    // 获取验证码
    private void getValidationCode() {
        String mobileStr = mMobileText.getString();

        boolean isMobile = CheckInputUtils.checkMobile(mobileStr, mMobilePointTextView);
        if (!isMobile) {
            return;
        }
        setCountDownTimmerView(COUNT_DOWN_MODE_LADING);
        showLoadingDialog(true, false, "正在获取验证码");
        mAccountBindVerifyController.handle(AcountBindVerifyCodeController.ACCOUNT_BIND_VALIDATION,
                mobileStr, mType);
    }

    // 点击下一步
    private void nextStepBind() {
        String mobileStr = mMobileText.getString();
        String validationCode = mValidationText.getText().toString();
        boolean isMobile = CheckInputUtils.checkMobile(mobileStr, mMobilePointTextView);
        if (!isMobile) {
            return;
        }
        if (!CheckInputUtils.checkVerifyCode(validationCode, mVerifyCodePointTextView)) {
            return;
        }
        if (mType == TYPE_BIND && isEmailOrMobileVipUser()) {
            mAccountBindController.bind(mobileStr, null, AccountBindModel.TYPE_BIND_PHOEN,
                    validationCode, null);
            mCurrentPhoneNumber = mobileStr;
            showLoadingDialog(true, false, "正在绑定");
        } else {

            mAccountBindVerifyController.handle(AcountBindVerifyCodeController.ACCOUNT_BIND_NEXT,
                    mobileStr, validationCode, mType);
            showLoadingDialog(true, false, "正在验证");
        }
    }

    private void handlerIntent() {
        Intent intent = getIntent();
        if (intent != null) {
            mType = intent.getIntExtra(INTENT_TYPE, 0);
        }
    }

    @Override
    public void activityLogicForward() {

    }

    @Override
    public void activityInitData() {

    }

    @Override
    public void onEvent(int event, final Object data) {
        switch (event) {
            case EventTypeConstants.EVENT_SUCCESS:
                Runnable r = new Runnable() {

                    @Override
                    public void run() {
                        onNetWorkCallback(data);

                    }
                };
                ShuqiApplication.getApplicationHandler().post(r);
                break;
            default:
                hideLoadingDialog();
                showMsg("网络连接超时");
                break;
        }

    }

    private void onNetWorkCallback(Object data) {

        if (data instanceof AccountBindGetValidationParser.AccountBindValidationInfo) {
            // 获取验证码返回
            hideLoadingDialog();
            AccountBindValidationInfo info = (AccountBindValidationInfo) data;
            if (info != null) {
                String msg = info.msg;
                if (!TextUtils.isEmpty(msg)) {
                    showMsg(msg);
                }
                if ("200".equals(info.state)) {
                    // 下发成功
                    setCountDownTimmerView(COUNT_DOWN_MODE_START);
                } else {
                    // 下发失败
                    setCountDownTimmerView(COUNT_DOWN_MODE_RESET);
                }
            }

        } else if (data instanceof AccountBindVerifyParser.AccountBindByPhoneInfo) {
            // 验证手机号和验证码接口返回
            AccountBindByPhoneInfo info = (AccountBindByPhoneInfo) data;
            hideLoadingDialog();
            if (info != null) {
                int code = Integer.parseInt(info.state);
                if (code == 200) {
                    // goto 设置密码页面
                    int type = PasswordSettingActivity.TYPE_BINDACCOUNT_BYPHONE;
                    if (mType == TYPE_FINDPASSWORD) {
                        type = PasswordSettingActivity.TYPE_FIND_PASSWORD_BYPHONE;
                    }
                    PasswordSettingActivity.show(this, type, AccountBindModel.TYPE_BIND_PHOEN,
                            info.phoneNumber, info.verifyCode);
                }
                String msg = info.msg;
                if (!TextUtils.isEmpty(msg)) {
                    showMsg(msg);
                }
            }

        } else if (data instanceof AccountBindParser.AccountBindParserInfo) {
            // 绑定手机号接口返回
            hideLoadingDialog();
            AccountBindParserInfo info = (AccountBindParserInfo) data;
            if (info != null) {
                int code = info.resultCode;
                if (code == 200) {
                    // 绑定成功
                    updateUserInfoToDB(info);
                    //跳转到用户绑定界面
                    AccountActivity.callRefreshAccountOnResume();
                    gotoAccountBindActivity();
                }
                String msg = info.message;
                if (!TextUtils.isEmpty(msg)) {
                    showMsg(msg);
                }
            }
        }
    }

    /** 回到绑定界面 */
    private void gotoAccountBindActivity() {
        Intent intent = new Intent(this, AccountBindActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        ActivityManager.getInstance().startNextActivity(intent, this);
    }

    /**
     * 
     * @param info 存入最新的用户信息
     */
    private void updateUserInfoToDB(AccountBindParserInfo info) {
        UserInfo user = MyAccountManager.getInstance(getApplicationContext());
        if (user == null) {
            return;
        }
        if (!TextUtils.isEmpty(mCurrentPhoneNumber)) {
            user.setMobile(mCurrentPhoneNumber);
        }
        if (!TextUtils.isEmpty(info.session)) {
            user.setSession(info.session);
        }
        AccountDao.getInstance().saveUserInfo(user);
    }


    private boolean isEmailOrMobileVipUser() {
        UserInfo user = MyAccountManager.getInstance(getApplicationContext(),true);
        return  MyAccountManager.isVipUserByEmailOrMobile(user);
    }

    private void showLoadingDialog(boolean isLoading, boolean isSuccess, String showText) {
        if (isFinishing()) {
            return;
        }
        if (mLoadingDialog == null) {
            mLoadingDialog = new ToastDialog(this);
            mLoadingDialog.setDissmisOnClickOutSide(false);
        }
        if (isLoading) {
            mLoadingDialog.loading(showText);
            return;
        }
        mLoadingDialog.setDissmisOnClickOutSide(true);
        mLoadingDialog.show(isSuccess, showText);

    }

    private void hideLoadingDialog() {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                if (mLoadingDialog != null) {
                    mLoadingDialog.dismiss();
                }
                setCountDownTimmerView(COUNT_DOWN_MODE_RESET);
            }
        };
        ShuqiApplication.getApplicationHandler().post(r);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mLoadingDialog != null) {
            mLoadingDialog.dismiss();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            ActivityManager.getInstance().finishActivity(this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        int id = v.getId();
        switch (id) {
            case R.id.edit_mobile:
                mMobileView.setSelected(hasFocus);
                break;
            case R.id.edit_validation:
                mValidationText.setSelected(hasFocus);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mAccountBindVerifyController != null) {
            mAccountBindVerifyController.onDestroy();
        }
        if (mAccountBindController != null) {
            mAccountBindController.onDestroy();
        }
    }

    /**
     * 
     * @param context
     * @param type (1001注册,1002绑定,1003找回密码)
     */
    public static void show(Activity context, int type) {
        Intent intent = new Intent(context, AccountMobileBindActivity.class);
        intent.putExtra(INTENT_TYPE, type);
        ActivityManager.getInstance().startNextActivity(intent, context);
    }

}
